package com.linyaonan.com.nio.selector.tcp.non_blocking_io;

import lombok.SneakyThrows;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @author: Lin
 * @date: 2020/11/15
 */
public class Server {

    @SneakyThrows
    public static void main(String[] args) {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 1. 设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        // 2. 绑定
        serverSocketChannel.bind(new InetSocketAddress(9999));
        // 3. 设置选择器
        Selector selector = Selector.open();
        // 4. 用于监听处理ACCEPT请求
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        // 5. 处理监听器响应的请求
        while (selector.select() > 0) {
            // 6. 就绪的连接集合
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                // 7. ACCEPT 请求
                if (selectionKey.isAcceptable()) {
                    // 准备就绪
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    // 设置为非阻塞
                    socketChannel.configureBlocking(false);
                    // 8. 将读请求进行注册
                    socketChannel.register(selector, SelectionKey.OP_READ);
                } else if (selectionKey.isReadable()) {
                    // 9. 处理读请求
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(128);
                    while (socketChannel.read(buffer) != -1) {
                        buffer.flip();
                        byte[] bytes = new byte[buffer.limit()];
                        buffer.get(bytes);
                        System.out.println(new String(bytes));
                        buffer.clear();
                    }
                }
                // 处理一个连接，需要进行删除
                iterator.remove();
            }
        }
    }
}
